package com.evil.application.config;

import cn.hutool.extra.servlet.ServletUtil;
import com.evil.common.core.constant.AppConstant;
import com.evil.common.core.enums.RCodeEnum;
import com.evil.common.core.exception.BusinessException;
import com.evil.common.log.constant.LogConstant;
import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author liyang
 * @date 2022-08-08 00:00
 */
@Slf4j
@Configuration
public class FeignHeaderConfiguration {

    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attrs != null) {
                HttpServletRequest request = attrs.getRequest();

                // cookie
                Cookie[] cookies = request.getCookies();
                if (cookies != null && cookies.length > 0) {
                    for (Cookie cookie : cookies) {
                        requestTemplate.header(cookie.getName(), cookie.getValue());
                    }
                }

                // header
                Enumeration<String> headerNames = request.getHeaderNames();
                if (headerNames != null) {
                    while (headerNames.hasMoreElements()) {
                        String name = headerNames.nextElement();
                        // 该类型不可以覆盖
                        if (name.equals(HttpHeaders.CONTENT_TYPE)) {
                            return;
                        }
                        String value = request.getHeader(name);
                        requestTemplate.header(name, value);
                    }
                }

                // requestUuid
                String requestUuid = request.getHeader(AppConstant.HEADER_REQUEST_UUID);
                if (StringUtils.isBlank(requestUuid)) {
                    throw new BusinessException(RCodeEnum.ERROR_RUNTIME, (Object) "requestUuid cannot be null");
                }

                // 请求日志
                Long requestLogId = (Long) request.getAttribute(LogConstant.OPERATE_LOG_HEADER);
                if (null != requestLogId) {
                    requestTemplate.header(LogConstant.OPERATE_LOG_HEADER, Long.toString(requestLogId));
                }

                // 自定义IP字段，防止转发服务时丢失
                requestTemplate.header(AppConstant.HEADER_REAL_IP_KEY, ServletUtil.getClientIP(request));
            }
        };
    }
}